//登录状态管理
import { defineStore } from 'pinia';
import { getUserProfile } from '../api/user.ts';

interface UserState {
  token: string | null;
  userInfo: Record<string, any> | null;
}

export const useAuthStore = defineStore('auth', {
  state: (): UserState => ({
    token: localStorage.getItem('token'),
    userInfo: null
  }),
  actions: {
    async loginSuccess(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
      await this.fetchUserInfo();
    },
    async fetchUserInfo() {
      try {
        const { data } = await getUserProfile();
        this.userInfo = data;
      } catch (error) {
        this.logout();
      }
    },
    logout() {
      this.token = null;
      this.userInfo = null;
      localStorage.removeItem('token');
    }
  }
});